import { AppConsts } from "@shared/AppConsts";
import { template } from "lodash";

export class HtmlHelper {

    static encodeText(value: string): string {
        let div = document.createElement('div');
        div[('textContent' in div) ? 'textContent' : 'innerText'] = value;
        return div.innerHTML;

    }

    static decodeText(value: string): string {
        let div = document.createElement('div') as any;
        div.innerHTML = value;
        return ('textContent' in div) ? div.textContent : div.innerText;
    }

    static encodeJson(jsonObject: object): string {
        return JSON.parse(this.encodeText(JSON.stringify(jsonObject)));
    }

    static decodeJson(jsonObject: object): string {
        return JSON.parse(this.decodeText(JSON.stringify(jsonObject)));
    }


    /**
     * html 解码
     * @param html 
     */
    static htmlDecode(html:string):string {
        if (!html) return "";
        let temp = "";
		if(html.length == 0) return "";
		temp = html.replace(/&amp;/g,"&");
		temp = temp.replace(/&lt;/g,"<");
		temp = temp.replace(/&gt;/g,">");
		temp = temp.replace(/&nbsp;/g," ");
		temp = temp.replace(/&#39;/g,"\'");
		temp = temp.replace(/&quot;/g,"\"");

        return temp;
    }

    /**
     * html 编码
     * @param html 
     */
    static htmlEncode(html:string):string {
        let temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        let output = temp.innerHTML;
        temp = null;
        return output;
    }


    static getOutputHtml(html: string): string{
        if (!html) {
            return html;
        }

        let remoteHostName = AppConsts.remoteServiceFileBaseUrl;
        return html
        .replace(new RegExp(remoteHostName,'g'), '[FileBaseUrl]');
    }
    static getInputHtml(html: string): string{
        if (!html) {
            return html;
        }

        let remoteHostName = AppConsts.remoteServiceFileBaseUrl;

        return html
        .replace(/\[FileBaseUrl\]/g, remoteHostName);
    }

    static truncate(value: string, max: number, tail = ' …', wordwise = false): string {
        if (value == null) {
            return null;
        }

        if (value.length <= max)
            return value;

        value = value.substring(0, max);
        if (wordwise) {
            var lastspace = value.lastIndexOf(' ');
            if (lastspace != -1) {
                value = value.substring(0, lastspace);
            }
        }
        return value + (tail || ' …');
    }
}
